var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,
    minHeight: 0,
    minWidth: 0,
    yu_e: 0,
    tiqu: '',
    tiquCoin: '',
    realGetCoin: 0,

    uid: 0,
    token: '',
    canMaxTiXian: 0,

    colorSet: '',
    waitTime: 0,

    hasShare: false,

    showAuthView: false,
    authToastData: '',

    showNavMPView: false
  },

  canCheckSubmit: true,

  lastGetCoinKey: "lgc_key",

  inviteuid: '',
  wxAuthFail: true,

  //其他小程序带过来的信息
  atherMPData: {
    isFormArherMP: false,
    atherMP_coin: 0,
    atherMP_orgid: '',
    atherMP_uid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: 'loading...',
    })

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight,
          minWidth: res.windowWidth,
          tc: app.get_tc()
        });
      },
    });

    //初始化第三方小程序带过来的参数："/pages/tixian/tixian?yuid=12780&coin=200&orgid=12779&hthongbao=1"
    this.atherMPData.isFormArherMP = (options.hthongbao == 1);
    this.atherMPData.atherMP_coin = options.coin ? parseInt(options.coin) : 0;
    this.atherMPData.atherMP_orgid = options.orgid ? options.orgid : '';
    this.atherMPData.atherMP_uid = options.yuid ? options.yuid : '';
    console.log("第三方小程序参数信息：", this.atherMPData);

    var curTime = parseInt(new Date().getTime() / 1000);
    var authTime = parseInt(util.shh_auth);
    var waitTime = 0;
    if (curTime > authTime) {
      waitTime = parseInt(100 - (curTime - authTime) / 3600 / 24);
    }
    this.setData({
      waitTime: waitTime
    })

    //是否是从 别的小程序转过来提现的
    var pages = getCurrentPages();
    var curPageIndex = pages.length;
    //如果是分享进来 或者 当前栈下标 是 1 都认为是分享进来的  因为分享人可能没授权登录 无法分享邀请码
    var isShare = curPageIndex <= 1;
    this.setData({
      hasShare: isShare
    })

  },

  //获取所有金额信息
  getCoinInfo: function () {
    if (this.atherMPData.isFormArherMP) {
      var that = this;
      // post方式请求，ac = cointoht，参数orgid原应用绑定uid、yuid原uid、txuid对应煌图uid、coin提现金额
      util.api({
        method: "POST",
        data: {
          ac: "cointoht",
          orgid: that.atherMPData.atherMP_orgid,
          yuid: that.atherMPData.atherMP_uid,
          coin: that.atherMPData.atherMP_coin,
          txuid: that.data.uid,
          uid: that.data.uid,
          privatekey: utilMd5.hexMD5(that.data.uid + 'cointoht' + that.data.token)
        },
        success: function (responseData) {
          var result = responseData.data;
          console.log("转移余额：", result);
          if (result.res) {
            that.atherMPData.isFormArherMP = false;
            that.getYu_e();
            that.getTixian();
          }
        }
      });
    } else {
      this.getYu_e();
      this.getTixian();
    }
  },

  onShow: function(){
    this.showAuthView(false, true);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });
  },
  //设置titlebar 样式
  resetNavColor: function () {
    var bg_color = '#f0f0f0';
    var fg_color = '#000000';
    if (this.data.colorSet) {
      bg_color = this.data.colorSet.titlebg;
      fg_color = this.data.colorSet.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  coinInputAction: function (e) {
    var inputStr = e.detail.value;
    var realGet = 0;
    if (inputStr) {
      var inputCoin = parseInt(parseFloat(inputStr) * 100);
      var realGet = ((inputCoin * 0.99) / 100).toFixed(2);
    }
    this.setData({
      realGetCoin: realGet
    });
  },

  all_tiqu: function () {
    var that = this;
    var allCanGetCoin = that.data.canMaxTiXian;
    var realGet = (((parseFloat(allCanGetCoin) * 100) * 0.99) / 100).toFixed(2);
    that.setData({
      tiqu: that.data.canMaxTiXian,
      realGetCoin: realGet
    });
  },

  formSubmit: function (e) {
    var that = this;
    
    if (!this.canCheckSubmit) {
      console.log("防止双击及连续点击");
      return;
    }
    this.canCheckSubmit = false;
    setTimeout(function () {
      console.log("复位防止双击及连续点击标识");
      that.canCheckSubmit = true;
    }, 1500);
    
    if (this.wxAuthFail) {
      this.showAuthView(false, true);
      return;
    }

    if (this.data.waitTime > 0) {
      var toast = "还需要等待 " + this.data.waitTime + " 天才能提现哦";
      wx.showModal({
        title: '提示',
        content: toast,
        showCancel: false
      })
      return;
    }

    var day = (new Date()).getDate();
    var lastGetCoinDay = wx.getStorageSync(this.lastGetCoinKey);
    console.log("day = " + day + "; lastGetCoinDay = " + lastGetCoinDay);
    if (day == lastGetCoinDay){
      wx.showModal({
        title: '提示',
        content: "您今天已经提现过一次了，明天再来吧",
        showCancel: false
      })
      return;
    }

    console.log("formId ", e.detail.formId);
    var txCoinStr = e.detail.value.tiqu_input;
    var tx_coin = txCoinStr ? parseFloat(txCoinStr): 0;
    console.log("tx_coin = " + tx_coin);
    that.setData({
      tiquCoin: parseInt(tx_coin * 100)
    });
    var minGetCoin = 1;
    if (tx_coin < minGetCoin) {
      var app1 = '最少提现' + minGetCoin + '元';
      app.dialog(app1, '提示');
    } else if (tx_coin > that.data.canMaxTiXian) {
      var app2 = '可提现余额不足';
      app.dialog(app2, '提示');
    } else {
      if (util.orgid == '11755') {//如果是煌图广告有限公司的小程序，那可以直接提现
        wx.showLoading({
          title: 'loading...',
          mask: "true"
        });
        //保存提现日期
        var day = (new Date()).getDate();
        wx.setStorageSync(that.lastGetCoinKey, day);
        //刷新本地余额数值
        that.refreshCoin_local();

        var data = {
          // ac: "extractcoin",
          // amount: tx_coin * 100,
          ac: "wxsendhongbao",
          total_fee: tx_coin * 100,
          uid: that.data.uid,
          "privatekey": utilMd5.hexMD5(that.data.uid + 'wxsendhongbao' + that.data.token)
        };
        console.log("wxsendhongbao: ", data);
        util.api({
          method: "POST",
          data: data,
          success: function (responseData) {
            var result = responseData.data;
            console.log("wxsendhongbao result ", result);
            wx.hideLoading();
            if (result.res) {
              wx.showModal({
                title: '提示',
                content: '已提交提现申请 24小时内到帐',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                }
              })
            } else {
              wx.showModal({
                title: '提示',
                content: result.msg,
                showCancel: false
              })
            }
          }
        });

      } else {//否则，去获取煌图广告公司的 小程序二维码，带上可提现余额数、用户id 等参数。
        
        var txCoin_fen = parseInt(tx_coin * 100);
        if (util.orgid == '12779' || util.orgid == '13147' || util.orgid == '13148' || util.orgid == '13150') {
          //未绑定同一个公众号，无法直接跳转，需要生成二维码进行扫码调转
          var url = "http://api.maxdoge.com/wxxcxcode.php?hthongbao=1&path=/pages/tixian/tixian&orgid=" + util.orgid + "&yuid=" + that.data.uid + "&coin=" + txCoin_fen;
          console.log("生产跳转二维码链接：" + url);
          wx.previewImage({
            current: url,
            urls: [url]
          })
        } else {
          that.showNavMPView();
        }
      }

    }
  },


  getYu_e: function () {
    var that = this;
    util.api({
      method: "POST",
      data: {
        ac: "coininfo",
        uid: that.data.uid,
        "privatekey": utilMd5.hexMD5(that.data.uid + 'coininfo' + that.data.token)
      },
      success: function (responseData) {
        var result = responseData.data;
        console.log("yu_e result ", result);
        if (result && result.coin) {
          that.setData({
            yu_e: (result.coin / 100.0).toFixed(2) //保留两位小数
          });
        }
      }
    });
  },

  //获取可提现金额
  getTixian: function () {
    var that = this;
    util.api({
      method: "GET",
      data: {
        ac: "gettixian",
        uid: that.data.uid,
        publickey: util.publiccode
      },
      success: function (responseData) {
        var result = responseData.data;
        console.log("gettixian result ", result);
        if (result && result.tixian) {
          var inputCoin = '';
          var realGet = 0;
          if (that.atherMPData.atherMP_coin > 0) {
            inputCoin = (that.atherMPData.atherMP_coin / 100).toFixed(2);
            realGet = (((inputCoin * 100) * 0.99) / 100).toFixed(2);
          }
          that.setData({
            canMaxTiXian: (result.tixian / 100.0).toFixed(2), //保留两位小数
            tiqu: inputCoin,
            realGetCoin: realGet
          });
        }
        wx.hideLoading();
      }
    });
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  goToHomePage: function () {
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },

  hideNavMPView: function () {
    this.setData({
      showNavMPView: false
    })
  },
  showNavMPView: function () {
    this.setData({
      showNavMPView: true
    })
  },
  //跳转到另一个小程序店家监听
  navigateToAtherMiniPro:function(){
    this.hideNavMPView();
    //保存提现日期
    var day = (new Date()).getDate();
    wx.setStorageSync(this.lastGetCoinKey, day);
    //刷新本地余额数值
    this.refreshCoin_local();
    wx.showLoading({
      title: 'loading...',
      mask: "true"
    })
    setTimeout(function () {
      wx.hideLoading();
    }, 2000)
  },

//本地刷新金额数值
  refreshCoin_local: function(){
    var nowYu_e = parseInt(parseFloat(this.data.yu_e) * 100) - this.data.tiquCoin;
    var nowCanGetYu_e = parseInt(parseFloat(this.data.canMaxTiXian) * 100) - this.data.tiquCoin;
    this.setData({
      yu_e: parseFloat(nowYu_e/100).toFixed(2),
      canMaxTiXian: parseFloat(nowCanGetYu_e / 100).toFixed(2)
    })
  },

  userCancelAuth: function () {//用户取消授权
    app.setLastUnAuthTime();
    this.hiddenAuthView();
  },
  showAuthView: function (showCancel, reAuth) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("已授权列表：", res);
        var authStatus_userInfo = res.authSetting["scope.userInfo"];
        if (authStatus_userInfo) {
          that.getLoginUserInfo();
        } else if (app.getShowAuthViewSign() || reAuth) {
          var authToastOb = {};
          authToastOb.showCancel = showCancel;
          authToastOb.msg = app.getBindOrgName() + " 需要您的授权"
          that.setData({
            showAuthView: true,
            authToastData: authToastOb
          })
        }
      }
    });
  },
  hiddenAuthView: function () {
    this.setData({
      showAuthView: false
    })
  },
  loginUserInfo: function (res) {
    if (res.detail.encryptedData) {//如果包含有这个字段，说明用户授权了
      this.getLoginUserInfo();
    } else {
      wx.redirectTo({
        url: 'pages/index/index',
      })
    }
  },

  getLoginUserInfo: function () {
    wx.showLoading({
      title: 'loading',
      mask: "true"
    })
    var that = this;
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      console.log("登录用户信息：", res);
      if (res && res != -1) {
        //更新数据
        that.wxAuthFail = false;
        that.setData({
          uid: res.uid,
          token: res.token
        });
        that.getCoinInfo();
      } else {
        wx.hideLoading();
      }

    }, that.inviteuid);
  }
})